package itbour.onetouchshow.activity.challengezone;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.alibaba.fastjson.JSON;
import com.andview.adapter.ABaseRefreshAdapter;
import com.andview.adapter.BaseRecyclerHolder;
import com.andview.listener.OnItemClickListener;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.utils.permission.Permission;
import com.video.cut.utils.TrimVideoUtil;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.challengezone.customvideopreview.CustomVideoPreviewActivity;
import itbour.onetouchshow.activity.challengezone.filter.GUPVideoplayActivity;
import itbour.onetouchshow.activity.challengezone.filter.VideoTimmerCutActivity;
import itbour.onetouchshow.activity.challengezone.video.MusicListActivity;
import itbour.onetouchshow.activity.challengezone.video.VideoRecordActivity;
import itbour.onetouchshow.activity.challengezone.video.VideoRecordQiNiuActivity;
import itbour.onetouchshow.adapter.base.recycler.BaseAdapter;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.bean.EffectsBean;
import itbour.onetouchshow.bean.FreeCreateOrigin;
import itbour.onetouchshow.bean.MusicInfoBean;
import itbour.onetouchshow.bean.PersonalCreateConfigBean;
import itbour.onetouchshow.bean.TransitionsBean;
import itbour.onetouchshow.bean.VideoSizeConfigBean;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.constants.DataCreater;
import itbour.onetouchshow.listener.PermissionListener;
import itbour.onetouchshow.utils.AssetsDataUtils;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.JumpUtils;
import itbour.onetouchshow.utils.StatusBarCompat;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.TypeCastHelper;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.widget.ScaleImageView;

import static itbour.onetouchshow.utils.UIUtils.getContext;
import static itbour.onetouchshow.utils.UIUtils.runInMainThread;


public class ChallengeZoneActivity extends MVPBaseActivity<ChallengeZoneContract.View, ChallengeZonePresenter>
        implements ChallengeZoneContract.View {

    //视频拍摄
    private static final int KEY_REQUEST_RECORD_VIDEO = 1;
    //背景音乐ID
    private static final int KEY_REQUEST_BGM_ID = 2;
    private static final int FAST_CLICK_DELAY_TIME = 2000;
    @BindView(R.id.id_root_ry)
    RelativeLayout idRootRy;
    @BindView(R.id.id_chall_work_ry)
    RecyclerView recyclerView;
    @BindView(R.id.id_ry_down)
    LinearLayout ryUploadTv;
    @BindView(R.id.tv_selet_tv)
    TextView tvSeletTv;
    @BindView(R.id.id_tv_recorded)
    TextView idTvRecorded;
    @BindView(R.id.id_tv_material)
    TextView idTvMaterial;
    @BindView(R.id.id_tv_synthesizing)
    TextView tvSynthesizing;
    @BindView(R.id.filter_listView)
    RecyclerView mFilterListView;
    @BindView(R.id.layout_filter)
    LinearLayout mFilterLayout;
    @BindView(R.id.id_ig_close)
    ImageView closeFilterLayout;
    @BindView(R.id.video_music_layout)
    LinearLayout selectVideoMusic;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.tv_rv_title)
    TextView tvrvTitle;
    @BindView(R.id.id_tv_music_name)
    TextView tvMusicName;
    @BindView(R.id.tv_time_duration)
    TextView tvTimeduration;
    @BindView(R.id.id_root_hint)
    LinearLayout rootHint;
    List<FreeCreateOrigin.MainAssetsBean> videoBeans;
    /**
     * 初始化切换转场的View
     */
    private ObjectAnimator animator;
    /**
     * 音乐
     */
    private List<MusicInfoBean> audioAssetsBeans;
    /**
     * 转场
     */
    private List<EffectsBean> effects;
    /**
     * 是否存草稿
     */
    private boolean isDRAFT;
    /**
     * 转场
     */
    private List<TransitionsBean> transitions;
    private TurnAdapter turnAdapter;
    private boolean isShow;
    private int maxTime;
    private boolean supportClearOneToOne = false;
    private long lastClickTime = 0L;
    private GirlAdapter baseRefreshAdapter;
    private View emptyView;
    private FreeCreateOrigin freeCreateOrigin;
    private List<TransitionsBean> itemTransitions;
    //默认制作
    private UserMakeTag userMakeTag = UserMakeTag.MAKE;
    /**
     * 当前选择的视频
     */
    private int currentSelectPosition = 0;
    private VideoSizeConfigBean configBean;
    //作品进来的模型
    private String jsonFreeCreateOriginModule;
    private String newUpdataJsonFreeCreateOriginModule;
    private int sizeId;
    /**
     * 拖动交换事件
     */
    private ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
        /**
         * 是否处理滑动事件 以及拖拽和滑动的方向 如果是列表类型的RecyclerView的只存在UP和DOWN，如果是网格类RecyclerView则还应该多有LEFT和RIGHT
         * @param recyclerView
         * @param viewHolder
         * @return
         */
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                        ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                final int swipeFlags = 0;
                return makeMovementFlags(dragFlags, swipeFlags);
            } else {
                final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                final int swipeFlags = 0;
                return makeMovementFlags(dragFlags, swipeFlags);
            }
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            //得到当拖拽的viewHolder的Position
            if (videoBeans.size() <= 1) return true;
            int fromPosition = viewHolder.getAdapterPosition();
            //拿到当前拖拽到的item的viewHolder
            int toPosition = target.getAdapterPosition();
            if (fromPosition < toPosition) {
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(videoBeans, i, i + 1);
                    if (itemTransitions != null) {
                        if (i + 1 < itemTransitions.size()) {
                            Collections.swap(itemTransitions, i, i + 1);
                        }
                    }
                }

            } else {
                //把后面的向前移动
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(videoBeans, i, i - 1);
                    if (itemTransitions != null) {
                        if (i < itemTransitions.size()) {
                            Collections.swap(itemTransitions, i, i - 1);
                        }
                    }
                }
            }
            //重新排序
            baseRefreshAdapter.notifyItemMoved(fromPosition, toPosition);
            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        }

        /**
         * 重写拖拽可用
         * @return
         */
        @Override
        public boolean isLongPressDragEnabled() {
            return videoBeans.size() <= 1;
        }

        /**
         * 长按选中Item的时候开始调用
         *
         * @param viewHolder
         * @param actionState
         */
        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                viewHolder.itemView.findViewById(R.id.id_reversal).setVisibility(View.INVISIBLE);
            }
            if (videoBeans.size() <= 1) {
                return;
            }
            super.onSelectedChanged(viewHolder, actionState);
        }

        /**
         * 手指松开的时候还原
         * @param recyclerView
         * @param viewHolder
         */
        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);
            if (videoBeans.size() <= 1) {
                return;
            }
            viewHolder.itemView.setBackgroundColor(0);
            /**
             * 拖动之后重新排序
             */
            AssetsDataUtils.swapTransitions(videoBeans, freeCreateOrigin.getTransition());
            baseRefreshAdapter.setNewData(videoBeans);
            setTvEnabled(videoBeans.size() <= 0);
        }
    });

    public static Intent getLaunchIntent(Context context, VideoSizeConfigBean videoSize) {
        Intent intent = new Intent(context, ChallengeZoneActivity.class);
        intent.putExtra(AppConst.KEY_VIDEO_SIZE_CONFIG, videoSize);
        return intent;
    }

    public static Intent getLaunchIntent(Context context, String freeCreateOrigin) {
        Intent intent = new Intent(context, ChallengeZoneActivity.class);
        intent.putExtra(AppConst.KEY_FREECRE, freeCreateOrigin);
        return intent;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_challenge_zone;
    }


    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        configBean = (VideoSizeConfigBean) getIntent().getSerializableExtra(AppConst.KEY_VIDEO_SIZE_CONFIG);
        jsonFreeCreateOriginModule = getIntent().getStringExtra(AppConst.KEY_FREECRE);
        if (jsonFreeCreateOriginModule != null) {
            freeCreateOrigin = new Gson().fromJson(jsonFreeCreateOriginModule, FreeCreateOrigin.class);
            videoBeans = freeCreateOrigin.getMainAssets();
            itemTransitions = freeCreateOrigin.getTransitions();
            audioAssetsBeans = freeCreateOrigin.getAudioAssets();
            effects = freeCreateOrigin.getEffects();
            userMakeTag = UserMakeTag.UPDATE;
        }
        if (freeCreateOrigin == null) {
            jsonFreeCreateOriginModule = "";
            createFreeCreateOriginModule();
            userMakeTag = UserMakeTag.MAKE;
        }
        if (videoBeans.size() >= 2) {
            tvTimeduration.setVisibility(View.VISIBLE);
            tvTimeduration.setText("总时长" + stringToDouble(TypeCastHelper.toString(freeCreateOrigin.getDuration())) + "S, 长按镜头可切换位置");
        } else {
            tvTimeduration.setVisibility(View.GONE);
        }
        if (audioAssetsBeans != null && audioAssetsBeans.size() != 0) {
            tvMusicName.setText(audioAssetsBeans.get(0).getName());
            tvMusicName.setBackgroundResource(0);
        }
        if (configBean == null) {
            List<VideoSizeConfigBean> videoSizeConfig = DataCreater.getVideoSizeConfig();
            for (int i = 0; i < videoSizeConfig.size(); i++) {
                if (videoSizeConfig.get(i).getWidth() == freeCreateOrigin.getWidth()) {
                    if (videoSizeConfig.get(i).getHeight() == freeCreateOrigin.getHeight()) {
                        configBean = videoSizeConfig.get(i);
                    }
                }
            }
        }
        newUpdataJsonFreeCreateOriginModule = jsonFreeCreateOriginModule;
        initRecycleView();
        initTurnRecycleView();
        setImmersionBarBlack();
    }

    @Override
    protected void setImmersionBarBlack() {
        StatusBarCompat.setStatusBarColor(this, UIUtils.getColor(R.color.black));
    }

    public void createFreeCreateOriginModule() {
        sizeId = configBean.getSizeId();
        freeCreateOrigin = new FreeCreateOrigin();
        freeCreateOrigin.setDuration(0);
        freeCreateOrigin.setWidth(configBean.getWidth());
        freeCreateOrigin.setHeight(configBean.getHeight());
        freeCreateOrigin.setCt(1105);
        videoBeans = new ArrayList<>();
        itemTransitions = new ArrayList<>();
        effects = new ArrayList<>();
        audioAssetsBeans = new ArrayList<>();
        freeCreateOrigin.setTransition(itemTransitions);
        freeCreateOrigin.setMainAssets(videoBeans);
        freeCreateOrigin.setEffects(effects);
        freeCreateOrigin.setAudioAssets(audioAssetsBeans);
    }


    @Override
    public void dataEvent(UserMakeTag userMakeTag) {
        if (userMakeTag.equals(UserMakeTag.DELETEVIDEO)) {
            int videoId = Integer.parseInt(userMakeTag.getTag());
            int index = 0;
            FreeCreateOrigin.MainAssetsBean rmoveMainAssetsBean = null;
            for (int i = 0; i < videoBeans.size(); i++) {
                if (videoBeans.get(i).getId() == videoId) {
                    rmoveMainAssetsBean = videoBeans.get(i);
                    index = i;
                }
            }
            for (int i = 0; i < effects.size(); i++) {
                if (effects.get(i).getId() == videoId) {
                    effects.remove(i);
                }
            }
            AssetsDataUtils.removeTransition(freeCreateOrigin, itemTransitions, videoBeans, index);
            freeCreateOrigin.setDuration(freeCreateOrigin.getDuration() - rmoveMainAssetsBean.getDuration());
            videoBeans.remove(index);
            AssetsDataUtils.swapTransitions(videoBeans, itemTransitions);
            freeCreateOrigin.setMainAssets(videoBeans);
            runInMainThread(new Runnable() {
                @Override
                public void run() {
                    baseRefreshAdapter.setNewData(videoBeans);
                    if (videoBeans.size() < 1) {
                        baseRefreshAdapter.isUseEmpty(true);
                    }
                    setTvEnabled(videoBeans.size() <= 0);
                }
            });


        } else if (userMakeTag.equals(UserMakeTag.ADDVIDEO)) {
            String videoUrl = userMakeTag.getTag();
            String imageCover = userMakeTag.getTag1();
            FreeCreateOrigin.MainAssetsBean mainAssetsBean = AssetsDataUtils.creatMainAssetsBeanMoudle(freeCreateOrigin, videoBeans, itemTransitions, videoUrl);
            mainAssetsBean.setCoverImage(imageCover);
            freeCreateOrigin.setMainAssets(videoBeans);
            if (videoBeans.size() > 1) {
                freeCreateOrigin.setTransition(itemTransitions);
            }
            baseRefreshAdapter.setNewData(videoBeans);
            setTvEnabled(videoBeans.size() <= 0);
            baseRefreshAdapter.isUseEmpty(false);
        } else if (userMakeTag.equals(UserMakeTag.UPDATE)) {
            String videoUrl = userMakeTag.getTag();
            int videoId = Integer.parseInt(userMakeTag.getTag1());
            String processedUrl = userMakeTag.getTag2();
            int[] videoWHDA = AssetsDataUtils.getVideoWHDA(videoUrl);
            EffectsBean effectsBean = userMakeTag.getEffectsBean();
            if (effectsBean != null) {
                effects.add(effectsBean);
            }
            int W = videoWHDA[0];
            int H = videoWHDA[1];
            int D = videoWHDA[2];
            int AN = videoWHDA[3];
            for (int i = 0; i < videoBeans.size(); i++) {
                if (videoBeans.get(i).getId() == videoId) {
                    videoBeans.get(i).setProcessedUrl(processedUrl);
                    videoBeans.get(i).setUrl(videoUrl);
                    videoBeans.get(i).setW(W);
                    videoBeans.get(i).setH(H);
                    videoBeans.get(i).setDuration(D);
                    videoBeans.get(i).setAn(AN);
                    baseRefreshAdapter.notifyItemChanged(i);
                }
            }
        }
        resetMainNodeStartTime();
        newUpdataJsonFreeCreateOriginModule = new Gson().toJson(freeCreateOrigin);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void initRecycleView() {
        baseRefreshAdapter = new GirlAdapter();
        recyclerView.setHasFixedSize(true);
        GridLayoutManager linearLayoutManager = new GridLayoutManager(getContext(), 2);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(recyclerView) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                //判断被拖拽的是否是前两个，如果不是则执行拖拽
                if (vh.getLayoutPosition() != 0 && vh.getLayoutPosition() != 1) {
                }
                mItemTouchHelper.startDrag(vh);
                //获取系统震动服务
                Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);//震动70毫秒
                vib.vibrate(70);
            }
        });

        mItemTouchHelper.attachToRecyclerView(recyclerView);
        baseRefreshAdapter.bindToRecyclerView(recyclerView);
        emptyView = UIUtils.inflate(R.layout.nodata_for_activity_chall);
        baseRefreshAdapter.setEmptyView(emptyView);
        if (videoBeans != null && videoBeans.size() != 0) {
            baseRefreshAdapter.addData(videoBeans);
            baseRefreshAdapter.isUseEmpty(false);
        } else {
            baseRefreshAdapter.isUseEmpty(true);
        }
        setTvEnabled(videoBeans.size() <= 0);
    }

    @SuppressLint("NewApi")
    public void initTurnRecycleView() {
        tvrvTitle.setText("设置转场效果");
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 4);
        mFilterListView.setLayoutManager(linearLayoutManager);
        PersonalCreateConfigBean customVideoConfigure = AssetsDataUtils.getCustomVideoConfigure();
        if (customVideoConfigure == null) return;
        transitions = customVideoConfigure.getTransitions();
        turnAdapter = new TurnAdapter(this, transitions, R.layout.filter_item_layout);
        mFilterListView.setAdapter(turnAdapter);
        turnAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseRecyclerHolder baseRecyclerHolder, int position, Object o) {
                turnAdapter.setSelect(position);
                TransitionsBean transitionsBean = transitions.get(position);
//                //当前选中除了转场ID全部替换
                TransitionsBean transitionsBean1 = itemTransitions.get(currentSelectPosition);
                AssetsDataUtils.swapTransitions(transitionsBean, transitionsBean1);
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        hideTurnView();
                    }
                }, 500);

            }
        });

        animator = ObjectAnimator.ofFloat(recyclerView, "rotation", 0, 360);
        animator.setDuration(500);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        closeFilterLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideTurnView();
            }
        });
    }

    @SuppressLint("NewApi")
    private void showTurnView() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(mFilterLayout, "translationY", mFilterLayout.getHeight(), 0);
        animator.setDuration(200);
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                mFilterLayout.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }
        });
        animator.start();
        baseRefreshAdapter.getIgReversal().setImageResource(R.mipmap.icon_reversal);
        isShow = !isShow;
    }

    @SuppressLint("NewApi")
    private void hideTurnView() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(mFilterLayout, "translationY", 0, mFilterLayout.getHeight());
        animator.setDuration(200);
        animator.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mFilterLayout.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                mFilterLayout.setVisibility(View.INVISIBLE);
            }
        });
        animator.start();
        if (baseRefreshAdapter.getIgReversal() != null) {
            baseRefreshAdapter.getIgReversal().setImageResource(R.mipmap.icon_unreversal);
        }
        isShow = !isShow;
    }

    /**
     * 从不同的界面返回 执行不同的操作
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (baseRefreshAdapter == null) {
            return;
        }
        //选择视频回调
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST: {
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    String videoUrl = null;
                    for (LocalMedia media : selectList) {
                        videoUrl = media.getPath();
                    }
                    Intent launchIntent = VideoTimmerCutActivity.getLaunchIntent(getContext(), videoUrl, UserMakeTag.ADDVIDEO.getTypeName());
                    startActivity(launchIntent);
                }
                break;
                case KEY_REQUEST_BGM_ID:
                    MusicInfoBean musicInfoBean = (MusicInfoBean) data.getSerializableExtra(AppConst.KEY_BGM_BEAN);
                    musicInfoBean.setCt(1404);
                    audioAssetsBeans.clear();
                    audioAssetsBeans.add(musicInfoBean);
                    tvMusicName.setText(musicInfoBean.getName());
                    tvMusicName.setBackgroundResource(0);
                    break;
                case KEY_REQUEST_RECORD_VIDEO:
                    //视频录制地址
                    String path = data.getStringExtra(AppConst.KEY_RECORD_VIDEO_PATH);
                    double durationCount = TypeCastHelper.toDouble(AssetsDataUtils.videoWHDA(path)[2]) / 1000 * 1.0;
                    if (durationCount < 3) {
                        T_.showToastReal("拍摄时间过短，无法裁剪");
                        return;
                    }
                    Intent launchIntent = VideoTimmerCutActivity.getLaunchIntent(getContext(), path, UserMakeTag.ADDVIDEO.getTypeName());
                    startActivity(launchIntent);
                    break;

            }
        }

    }

    @Override
    public void loadSucceed(String result) {
        dismissProgressDialog();
        newUpdataJsonFreeCreateOriginModule = new Gson().toJson(freeCreateOrigin);
        jsonFreeCreateOriginModule = newUpdataJsonFreeCreateOriginModule;
        if (isDRAFT) {
            T_.showToastReal("存草稿成功");
            return;
        }
        String docId = null;
        if (userMakeTag.equals(UserMakeTag.MAKE)) {
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
            docId = jsonObject.getString("docId");
            userMakeTag = UserMakeTag.UPDATE;
            freeCreateOrigin.setDocId(Integer.valueOf(docId));
        } else if (UserMakeTag.UPDATE.equals(userMakeTag)) {
            docId = freeCreateOrigin.getDocId() + "";
        }
        Intent launchIntent = CustomVideoPreviewActivity.getLaunchIntent(getContext(), docId, UserMakeTag.MAKE.getTypeName());
        startActivity(launchIntent);

    }

    @Override
    public void loadFaild(String error) {
        dismissProgressDialog();
        T_.showToastReal(error);
    }

    @OnClick({R.id.tv_selet_tv, R.id.id_tv_recorded, R.id.id_tv_material, R.id.id_tv_synthesizing, R.id.id_ry_down, R.id.video_music_layout
            , R.id.id_ly_record, R.id.tv_save, R.id.tv_next, R.id.iv_back, R.id.layout_filter, R.id.id_root_hint})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_ry_down:
            case R.id.tv_selet_tv:
                if (freeCreateOrigin.getDuration() > 57) {
                    showVideoToLongDialog();
                    return;
                }
                TrimVideoUtil.MAX_SHOOT_DURATION = (long) ((AppConst.MAXRECORDSECONDS - freeCreateOrigin.getDuration()) * 1000L);
                requestPermission(new PermissionListener() {
                    @Override
                    public void onGranted() {
                        JumpUtils.gotoSelectType(ChallengeZoneActivity.this);
                    }

                    @Override
                    public void onDenied(List<String> list) {
                    }
                }, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE);

                break;
            case R.id.id_tv_synthesizing:
                showProgressDialogWithText("合成视频中....");
                mPresenter.onloadNet(freeCreateOrigin);
                break;
            case R.id.video_music_layout:
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                requestPermission(new PermissionListener() {
                    @Override
                    public void onGranted() {
                        startActivityForResult(MusicListActivity.getLaunchIntent(getViewContext()), KEY_REQUEST_BGM_ID);
                    }

                    @Override
                    public void onDenied(List<String> list) {
                    }
                }, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE);
                break;
            case R.id.id_ly_record:
                if (freeCreateOrigin.getDuration() > 57) {
                    showVideoToLongDialog();
                    return;
                }
                maxTime = (int) (AppConst.MAXRECORDSECONDS - freeCreateOrigin.getDuration());
                TrimVideoUtil.MAX_SHOOT_DURATION = (long) ((AppConst.MAXRECORDSECONDS - freeCreateOrigin.getDuration()) * 1000L);
                // TrimVideoUtil.MAX_SHOOT_DURATION = maxTime;
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                requestPermission(new PermissionListener() {
                    @Override
                    public void onGranted() {
                        if (supportClearOneToOne && configBean.getWidth() == configBean.getHeight()) {
                            Camera mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
                            Camera.Parameters params = mCamera.getParameters();
                            Camera.Size size = getCloselyVideoSize(true, 960, 960, params.getSupportedVideoSizes());
                            mCamera.release();
                            mCamera = null;
                            if (960 - size.width > 480) {
                                //支持的分辨率差距 是否超过480
                                startActivityForResult(VideoRecordQiNiuActivity.getLaunchIntent(getContext(), maxTime), KEY_REQUEST_RECORD_VIDEO);
                            } else {
                                startActivityForResult(VideoRecordActivity.getLaunchIntent(getViewContext(), configBean, maxTime), KEY_REQUEST_RECORD_VIDEO);
                            }
                        } else {
                            startActivityForResult(VideoRecordActivity.getLaunchIntent(getViewContext(), configBean, maxTime), KEY_REQUEST_RECORD_VIDEO);
                        }
                    }

                    @Override
                    public void onDenied(List<String> list) {

                    }
                }, Permission.CAMERA, Permission.RECORD_AUDIO);
                break;
            case R.id.tv_save:
                isDRAFT = true;
                showProgressDialogWithText("正在存草稿....");
                resetMainNodeStartTime();
                if (userMakeTag == UserMakeTag.UPDATE) {
                    mPresenter.updataCustomVideoDoc(freeCreateOrigin, freeCreateOrigin.getDocId() + "");
                } else if (userMakeTag.equals(UserMakeTag.MAKE)) {
                    mPresenter.newCustomVideoDoc(freeCreateOrigin, sizeId);
                }
                break;
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.tv_next:
                isDRAFT = false;
                showProgressDialogWithText("合成视频中....");
                resetMainNodeStartTime();
                if (userMakeTag == UserMakeTag.UPDATE) {
                    mPresenter.updataCustomVideoDoc(freeCreateOrigin, freeCreateOrigin.getDocId() + "");
                } else if (userMakeTag.equals(UserMakeTag.MAKE)) {
                    mPresenter.newCustomVideoDoc(freeCreateOrigin, sizeId);
                }
                break;
            case R.id.id_root_hint:
                if (isShow) {
                    hideTurnView();
                }
                break;

        }
    }

    @Override
    public void onBackPressed() {
        dismissProgressDialog();
        if (jsonFreeCreateOriginModule.equals(newUpdataJsonFreeCreateOriginModule)) {
            super.onBackPressed();
        } else {
            showSaveDialog();
        }
    }

    public void showVideoToLongDialog() {
        new OneToucDialog.Builder(this)
                .content("总时长已达到最长，请删除或裁剪部分镜头后重新上传拍摄")
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false)
                .show();
    }

    public void showSaveDialog() {
        new OneToucDialog.Builder(this)
                .content("是否保存本次编辑并退出")
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                isDRAFT = true;
                showProgressDialogWithText("正在存草稿....");
                resetMainNodeStartTime();
                if (userMakeTag == UserMakeTag.UPDATE) {
                    mPresenter.updataCustomVideoDoc(freeCreateOrigin, freeCreateOrigin.getDocId() + "");
                } else if (userMakeTag.equals(UserMakeTag.MAKE)) {
                    mPresenter.newCustomVideoDoc(freeCreateOrigin, sizeId);
                }
                finish();
            }
        })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                finish();
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false)
                .show();


    }

    public void resetMainNodeStartTime() {
        for (int i = 0; i < videoBeans.size(); i++) {
            if (i == 0) {
                videoBeans.get(0).setStart(0);
            } else {
                FreeCreateOrigin.MainAssetsBean mainAssetsBean = videoBeans.get(i - 1);
                videoBeans.get(i).setStart(mainAssetsBean.getDuration() + mainAssetsBean.getStart());

            }
        }
        resetTransition();
        resetDuration();
    }

    public void resetDuration() {
        for (int i = 0; i < videoBeans.size(); i++) {
            if (i == videoBeans.size() - 1) {
                double duration = videoBeans.get(i).getStart() + videoBeans.get(i).getDuration();
                freeCreateOrigin.setDuration(duration);
            }
        }
        if (tvTimeduration != null) {
            if (videoBeans.size() >= 2) {
                tvTimeduration.setVisibility(View.VISIBLE);
                tvTimeduration.setText("总时长" + stringToDouble(TypeCastHelper.toString(freeCreateOrigin.getDuration())) + "S, 长按镜头可切换位置");
            } else {
                tvTimeduration.setVisibility(View.GONE);
            }
        }

    }

    /**
     * 删除一个转场
     */
    public void resetTransition() {
        if (videoBeans.size() >= 2) {
            /**
             * 得到原来数据交换新Id 移到目标后面的所有连续ID都得+1 toPosition
             */
            if (itemTransitions.size() > 1 && itemTransitions != null) {
                for (int i = 0; i < itemTransitions.size(); i++) {
                    TransitionsBean transition = itemTransitions.get(i);//0   12
                    FreeCreateOrigin.MainAssetsBean mainAssetsBean = videoBeans.get(i);//0   12
                    Integer startinteger = mainAssetsBean.getId();
                    Integer endinteger = videoBeans.get(i + 1).getId();
                    List<Integer> newid = new ArrayList<>();
                    newid.add(startinteger);
                    newid.add(endinteger);
                    transition.setAssetid(newid);
                }
            }

        } else {
            if (itemTransitions != null && itemTransitions.size() == 1) {
                itemTransitions.remove(0);
            }
        }
    }


    public void setTvEnabled(boolean enabled) {
        if (tvNext == null) return;
        if (tvSave == null) return;
        if (enabled) {
            tvNext.setTextColor(UIUtils.getColor(R.color.line_button));
            tvNext.setEnabled(false);
            tvSave.setTextColor(UIUtils.getColor(R.color.line_button));
            tvSave.setEnabled(false);
        } else {
            tvNext.setTextColor(UIUtils.getColor(R.color.white));
            tvNext.setEnabled(true);
            tvSave.setTextColor(UIUtils.getColor(R.color.white));
            tvSave.setEnabled(true);
        }
    }

    //通过对比得到与编码尺寸最相近 摄像头支持的输出比例
    public Camera.Size getCloselyVideoSize(boolean isPortrait, int surfaceWidth, int surfaceHeight, List<Camera.Size> videoSizeList) {
        if (videoSizeList != null && videoSizeList.size() > 0) {
            //机型适配 有些机型获取的preSizeList顺序是从小到大的
            if (videoSizeList.get(videoSizeList.size() - 1).width > videoSizeList.get(0).width) {
                Collections.reverse(videoSizeList);
            }
        }

        int reqTmpWidth;
        int reqTmpHeight;
        // 当屏幕为垂直的时候需要把宽高值进行调换，保证宽大于高
        if (isPortrait) {
            reqTmpWidth = surfaceHeight;
            reqTmpHeight = surfaceWidth;
        } else {
            reqTmpWidth = surfaceWidth;
            reqTmpHeight = surfaceHeight;
        }
        //先查找preview中是否存在与SurfaceView相同宽高的尺寸
        for (Camera.Size size : videoSizeList) {
            if ((size.width == reqTmpWidth) && (size.height == reqTmpHeight)) {
                return size;
            }
        }

        // 得到与传入的宽高比最接近的size
        float reqRatio = ((float) reqTmpWidth) / reqTmpHeight;
        float curRatio, deltaRatio;
        float deltaRatioMin = Float.MAX_VALUE;
        Camera.Size retSize = null;
        for (Camera.Size size : videoSizeList) {
            curRatio = ((float) size.width) / size.height;
            deltaRatio = Math.abs(reqRatio - curRatio);
            if (deltaRatio < deltaRatioMin) {
                deltaRatioMin = deltaRatio;
                retSize = size;
            }
        }
        return retSize;

    }

    public int getSelectTransitionsPosition(TransitionsBean transitionsBean) {
        for (int i = 0; i < transitions.size(); i++) {
            if (transitions.get(i).getDbId() == transitionsBean.getDbId()) {
                return i;
            }
        }
        return 0;
    }

    /**
     * String转换成double 保留N位小数。
     *
     * @param a
     * @return
     */
    public double stringToDouble(String a) {
        double b = Double.valueOf(a);
        DecimalFormat df = new DecimalFormat("#.0");//此为保留1位小数，若想保留2位小数，则填写#.00  ，以此类推
        String temp = df.format(b);
        b = Double.valueOf(temp);
        return b;
    }

    public class TurnAdapter extends ABaseRefreshAdapter<TransitionsBean> {
        private int selected = 0;

        public TurnAdapter(Context context, List<TransitionsBean> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        public void setSelect(int position) {
            if (selected == position)
                return;
            int lastSelected = selected;
            selected = position;
            notifyItemChanged(lastSelected);
            notifyItemChanged(selected);
        }

        @SuppressLint("NewApi")
        @Override
        protected void convert(BaseRecyclerHolder baseRecyclerHolder, TransitionsBean magicFilterType, int position) {
            FrameLayout frameLayout = baseRecyclerHolder.getView(R.id.filter_root);
            ImageView thumbImage = baseRecyclerHolder.getView(R.id.filter_thumb_image);
            TextView filterName = baseRecyclerHolder.getView(R.id.filter_thumb_name);
            FrameLayout thumbSelected = baseRecyclerHolder.getView(R.id.filter_thumb_selected);
            View thumbSelected_bg = baseRecyclerHolder.getView(R.id.filter_thumb_selected_bg);
            if (position == selected) {
                thumbSelected.setVisibility(View.VISIBLE);
                thumbSelected_bg.setBackgroundColor(Color.LTGRAY);
                thumbSelected_bg.setAlpha(0.7f);
            } else {
                thumbSelected.setVisibility(View.GONE);
            }
            ImageLoader.getInstance().showImage(getContext(), magicFilterType.getIcon(), thumbImage);
            filterName.setText(magicFilterType.getName());
        }
    }

    public class GirlAdapter extends BaseAdapter<FreeCreateOrigin.MainAssetsBean, BaseViewHolder> {
        int count = 0;
        ImageView mIgReversal;

        public GirlAdapter() {
            super(R.layout.item_chall_zone);
        }

        public void deleteItem(int position) {
            remove(position);
            notifyDataSetChanged();
        }

        public ImageView getIgReversal() {
            return mIgReversal;
        }

        public void setmIgReversal(ImageView mIgReversal) {
            this.mIgReversal = mIgReversal;
        }


        @Override
        protected void convert(BaseViewHolder helper, FreeCreateOrigin.MainAssetsBean videoBean, int position) {
            if (videoBean == null) {
                return;
            }
            ScaleImageView imageView = helper.getView(R.id.id_ig_temp);
            TextView tvTime = helper.getView(R.id.id_tv_time);
            ImageView igReversal = helper.getView(R.id.id_reversal);
            int width = UIUtils.dip2px(120);
            imageView.setInitSize(width, width / 3 * 2);
            if (videoBean.getCoverImage() != null) {
                ImageLoader.getInstance().showCircleImageWithBorderCenterCrop(getContext(), videoBean.getCoverImage(), imageView);
            } else {
                //  imageView.setImageBitmap(ImageLoader.getInstance().getVideoThumbnail(videoBean.getUrl()));
            }
            //得到秒
            // double startduration =  videoBean.getDuration() * 1000L;
            // int duration = (int) (Math.ceil(startduration / 10.0 / 10.0) / 10);
            tvTime.setText(itbour.onetouchshow.utils.DateUtils.timeParse(TypeCastHelper.toLong(videoBean.getDuration() * 1000L)));
            // tvName.setText("自由创建作品" + videoBean.getId());
            if (position == videoBeans.size() - 1) {
                igReversal.setVisibility(View.INVISIBLE);
            } else {
                igReversal.setVisibility(View.VISIBLE);
            }
            igReversal.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mIgReversal = igReversal;
                    currentSelectPosition = position;
                    if (itemTransitions != null) {
                        TransitionsBean transitionsBean = itemTransitions.get(position);
                        int selectTransitionsPosition = getSelectTransitionsPosition(transitionsBean);
                        turnAdapter.setSelect(selectTransitionsPosition);
                    } else {
                        turnAdapter.setSelect(0);
                    }
                    showTurnView();

                }
            });
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EffectsBean effectsBean = null;
                    for (int i = 0; i < effects.size(); i++) {
                        if (effects.get(i).getId() == videoBean.getId()) {
                            effectsBean = effects.get(i);
                        }
                    }
                    TrimVideoUtil.MAX_SHOOT_DURATION = AppConst.MAXRECORDSECONDS * 1000L;
//                    Intent launchIntent = GUPVideoplayActivity.getLaunchIntent(getContext(), videoBeans.get(position).getUrl()
//                                    , videoBeans.get(position).getId(), effectsBean);

                    Intent launchIntent = GUPVideoplayActivity.getLaunchIntent(getContext(), effectsBean, videoBeans.get(position));
                    startActivity(launchIntent);
                }
            });
            count++;
        }
    }

    /**
     * 长按事件
     */
    public abstract class OnRecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
        private GestureDetectorCompat mGestureDetector;
        private RecyclerView recyclerView;

        public OnRecyclerItemClickListener(RecyclerView recyclerView) {
            this.recyclerView = recyclerView;
            mGestureDetector = new GestureDetectorCompat(recyclerView.getContext(), new ItemTouchHelperGestureListener());
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            mGestureDetector.onTouchEvent(e);
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
            mGestureDetector.onTouchEvent(e);
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        }

        public abstract void onItemClick(RecyclerView.ViewHolder vh);

        public abstract void onItemLongClick(RecyclerView.ViewHolder vh);

        private class ItemTouchHelperGestureListener extends GestureDetector.SimpleOnGestureListener {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null) {
                    RecyclerView.ViewHolder vh = recyclerView.getChildViewHolder(child);
                    onItemClick(vh);
                }
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null) {
                    RecyclerView.ViewHolder vh = recyclerView.getChildViewHolder(child);
                    onItemLongClick(vh);
                }
            }
        }
    }


}
